﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace WinHBM.Core
{

    [Serializable]
    public class UserInfo
    {

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(UserInfo));

        public int Id { get; set; }

        public string LoginId { get; set; }

        public string Password { get; set; }

        public string Address { get; set; }

        public bool Auto { get; set; }
        public int ClassId { get; set; }
        private static UserInfo _instance;

        public static UserInfo INSTANCE
        {
            get
            {
                if(_instance == null)
                {
                    if(!ResloveUserInfo())
                    {
                        _instance = new UserInfo();
                    }
                }
                return _instance;
            }
        }

        private static bool ResloveUserInfo()
        {
            FileStream fs = null;
            UserInfo user = null;
            try
            {
                //读取文件流对象 
                fs = new FileStream("user.bin", FileMode.Open);
                if (fs.Length > 0)
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    //读出存在user.bin 里的用户信息
                    _instance = bf.Deserialize(fs) as UserInfo;
                    return true;
                }

            }
            catch (Exception e)
            {
                Logger.Debug(e);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            return false;
        }

        public bool commit()
        {
            FileStream fs = null;
            UserInfo user = null;
            try
            {
                //读取文件流对象 
                fs = new FileStream("user.bin", FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, _instance);
                return true;
            }
            catch (Exception e)
            {
                Logger.Debug(e);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            return false;
        }

    }
}
